<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/common/includes.jsp"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>调拨发起编辑</title>
<!-- import css and js -->
<%@ include file="/common/metaInput.jsp"%>
<script src="${ctx}/js/jsp/comm.js" type="text/javascript"></script>
<script type="text/javascript" src="${ctx}/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="${ctx}/js/jsp/yd/logic/ItemStateData.js"></script>
<script src="${ctx}/js/jsp/date.js" type="text/javascript"></script>
<script type="text/javascript">
	var basic_Url = "${ctx}/yd/logic/stockTransferStart";
	var addressGrid;
	$(function() {
		
		$("#outwhcode").change(function(){ 
			$("#outwhname").val($("#outwhcode").find("option:selected").text());
			$("#outwhcode").val($("#outwhcode").val());
			var manager = $("#dataGrid1").ligerGetGridManager(); 
			manager.loadData(); 
		}); 
		
		$("#inwhcode").change(function(){ 
			$("#inwhname").val($("#inwhcode").find("option:selected").text());
			$("#inwhcode").val($("#inwhcode").val());
		}); 
		
	 	$("#inputForm").validate({
			onsubmit : true,
			//执行ajaxsubmit  
			submitHandler : function(editform) {

				try {
					url = basic_Url + "/save.do";
					var api = frameElement.api;
					var W = api.opener;
					getReturnMessage(url, "inputForm", W.searchAP);
				} catch (e) {
					alert(e);
				}
			}
		}); 
	 	
	 	if ('${oi.billstatus}' == ''){
			$("#save1").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("#save4").hide();
			$("#save5").hide();
		}else if ('${oi.billstatus}' == "0"){
			$("#save").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("#save4").hide();
			$("#save5").hide();
			$("select[id='outwhcode']").attr("disabled",true);//禁用出货仓SELECT标签 
            if($("#aegnt").val()!="${user.name}"){
    			$("#save1").hide();
    			$("input[type!='hidden']").attr("disabled",true);//禁用SELECT标签
    			$("select").attr("disabled",true);//禁用SELECT标签
    			$("textarea").attr("disabled",true);//禁用TEXTAREA标签
               }  
		}else if ('${oi.billstatus}' == "1"){
			$("#save").hide();
			$("#save1").hide();
			$("#save4").hide();
			$("input[type!='hidden']").attr("disabled",true);//禁用SELECT标签
			$("select").attr("disabled",true);//禁用SELECT标签
			$("textarea").attr("disabled",true);//禁用TEXTAREA标签
		}else if ('${oi.billstatus}' == "2"){
			$("#save").hide();
			$("#save1").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("input[type!='hidden']").attr("disabled",true);//禁用SELECT标签
			$("select").attr("disabled",true);//禁用SELECT标签
			$("textarea").attr("disabled",true);//禁用TEXTAREA标签
		}else if ('${oi.billstatus}' == "3"){
			$("#save").hide();
			$("#save1").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("#save4").hide();
			$("#save5").hide();
			$("input[type!='hidden']").attr("disabled",true);//禁用SELECT标签
			$("select").attr("disabled",true);//禁用SELECT标签
			$("textarea").attr("disabled",true);//禁用TEXTAREA标签
		}else{
			$("#save").hide();
			$("#save1").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("#save4").hide();
			$("#save5").hide();
			$("input[type!='hidden']").attr("disabled",true);//禁用input标签
			$("select").attr("disabled",true);//禁用SELECT标签
			$("textarea").attr("disabled",true);//禁用TEXTAREA标签
		}
	});
		
	function submitForm(param) {
		var data = $("#dataGrid1").ligerGetGridManager().getData();
		if(data.length==0){
			$.dialog.alert("请增加物料信息");
	   	 	return false;
		}
		var ba=true;
		if($("#outwhname").val()==$("#inwhname").val()){
			 $.dialog.alert("您的送货仓与收货仓一样，请修改！");
        		ba = false;
        		return;
		}
		if(data !=null){ 
			for (var i = 0;i < data.length;i++){
				var row = data[i];
				if(undefined == row.status || row.status==null||row.status==''){
					$.dialog.alert("您第"+(i+1)+"行的状态没有选择");
	           		ba = false;
	           		return;
				}
				if(undefined == row.unit || row.unit==null||row.unit==''){
					$.dialog.alert("您第"+(i+1)+"行的单位没有选择");
	           		ba = false;
	           		return;
				}
				if(undefined == row.quantity || row.quantity==null || row.quantity <= 0){
	           	 $.dialog.alert("您第"+(i+1)+"行的调拨数量不合法");
	           		ba = false;
	           		return;
	            }
				if((parseFloat(row.quantity))>parseFloat(row.inquantity)){
					$.dialog.alert("您第" + (i+1) + "行的调拨数量大于库存数量");
					ba = false;
					return false;
				}
		        if(undefined == row.bzq
						|| isNaN(row.bzq)
						|| row.bzq <= 0){
		           	 $.dialog.alert("您第"+(i+1)+"行的“保质期”不合法");
		           	 ba=false;
		           	 return false;
		        }
		        if(undefined == row.scrq || null==row.scrq||""==row.scrq){
		           	 $.dialog.alert("您第"+(i+1)+"行的“生产/采购日期”未选择");
		           	 ba=false;
		           	 return false;
		        }
		        if(undefined == row.yxq || null==row.yxq||""==row.yxq){
		           	 $.dialog.alert("您第"+(i+1)+"行的“有效期”未选择");
		           	 ba=false;
		           	 return false;
		        } 
			}
		}
		if (ba){
			$("#billstatus").val(param);
			$("#addressInfos").val(JSON.stringify(data));
			$("#submitFlag").val(param);
			$("#inputForm").submit();
		}
	}
	
	function check(){
		$.ajax({
		      url: "${ctx}/yd/logic/stockTransferStart/updateState.do",
		      global: false,
		      type: "POST",
		      dataType: "json",
		      data: ({
		    	   rows:$("#id").val()
		      }),		     
		      success: function(msg){
		    	  if(msg.msg=="SUCCESS"){
		    		  $.dialog.alert("驳回成功",function(){close();});
		    	  }
		    	  if(msg.msg=="ERROR"){
		    		  $.dialog.alert("操作失败",function(){close();});
		    	  }
		   }
		});
	}
    
	function close(){
		var api = frameElement.api;
		var W = api.opener;
		CloseDialog();
		W.searchAP();
	}
	
</script>

</head>

<body onload="">

	<form id="inputForm" action="" method="post">
		<input type="hidden" id="id" name="id" value="${oi.id}" />
		<input type="hidden" id="version" name="version" value="${oi.version}" />
		<input type="hidden" id="addressInfos" name="addressInfos"/>
		<input type="hidden" id="dataItem" name="dataItem"/>
	<!-- 	<input type="hidden" id="batchItem" name="batchItem"/> -->
		<input type="hidden" id="billstatus" name="billstatus" value="${oi.billstatus}"/>
		<!-- 用于标识提交按钮 -->
		<input type="hidden" id="submitFlag" value="" />
		<div class="pageContent">
			<div class="panel">
				<table class="TableBlock" align="center">
					<c:if test="${!empty oi.otheroutwhcode}">
					<tr >
						<td nowrap="nowrap" width="20%">调拨发起单号:</td>
						<td width="30%"><input id="otheroutwhcode" name="otheroutwhcode" readonly="readonly"  class="inp_width_98p" value="${oi.otheroutwhcode}" /></td>
						<td nowrap="nowrap" width="20%">建单时间:</td>
						<td width="30%"><input class="inp_width_98p" type="text" id="dctime" name="dctime"
							value="<fmt:formatDate value="${empty oi.dctime?nowDate:oi.dctime}" type="both" dateStyle="long" pattern="yyyy-MM-dd" />" readonly="readonly"/></td>
					</tr>
				</c:if>
					<tr>
						<td nowrap="nowrap" width="20%">送货仓:</td>
						<td width="30%"><select id="outwhcode" class="inp_width_98p required" name="outwhcode" >
						 	<option></option>
								<c:forEach items='${wh}' var='state'>
   		                 	<option id='${state.id}' value='${state.code}'>${state.name}</option>
   		                 	</c:forEach>
							</select>
							<script type="text/javascript">
   		                		 $("#outwhcode").val('${oi.outwhcode}');
   		                 	</script>
   		             		<input type="hidden" id="outwhname" name="outwhname" value="${oi.outwhname }"/>
   		             	</td>
						<td nowrap="nowrap" width="20%">收货仓:</td>
						<td width="30%"><select id="inwhcode" class="inp_width_98p required" name="inwhcode" >
							<option></option>
								<c:forEach items='${wh1}' var='state'>
   		                 	<option id='${state.id}' value='${state.code}'>${state.name}</option>
   		                 	</c:forEach>
							</select>
							<script type="text/javascript">
   		                		 $("#inwhcode").val('${oi.inwhcode}');
   		                 	</script>
   		             		<input type="hidden" id="inwhname" name="inwhname" value="${oi.inwhname }"/>
   		             	</td>
					</tr>
					<tr>
						<td nowrap="nowrap" width="20%">转库日期:</td>
						<td width="30%">
							<input id="zkrq" name="zkrq" class="inp_width_98p required" onclick="WdatePicker({dateFmt:'yyyy-MM-dd'})"
							value="<fmt:formatDate value="${oi.zkrq}" pattern="yyyy-MM-dd" type="both" />" />
							<c:if test="${oi.zkrq == null}">
								<script>
									var date = new Date();
									$("#zkrq").val(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
								</script>
							</c:if>
						</td>
						<td nowrap="nowrap" width="20%">制单人:</td>
						<td width="30%">
							<input type="text" id="aegnt" name="aegnt" class="inp_width_98p" value="${user.name}" readonly="readonly"/>
							<c:if test="${oi.aegnt != null}">
								<script>
									$("#aegnt").val("${oi.aegnt}");
								</script>
							</c:if>
						</td>
					</tr>
   		           <tr>
   		           		 	<td>备注:</td>
   		           	<td colspan="3"><input id="remark" type="text" class="inp_width_98p" name="remark" value="${oi.remark}" /></td>
   		           </tr>
					<tr>
						<td colspan="4" style="margin-bottom: 10px;"><div
								id="dataGrid1"></div>
								 </td>  
					</tr>
				</table>
			</div>
			<div class="formBar">
				<ul>
					 <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save" onclick="submitForm(0)">保存</button></div></div></li>
					 <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save1" onclick="submitForm(1)">提交</button></div></div></li>
				<webres:displaycontroller elementId="LOGIC_TRSTART_2SEHNHE" description="调拨发起单二级审核">
			       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save2" onclick="submitForm(2)" title="提交三级审核">二级审核</button></div></div></li>
		       	</webres:displaycontroller>
				<webres:displaycontroller elementId="LOGIC_TRSTART_2WANJIE" description="调拨发起单二审完结">
			       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save3" onclick="submitForm(3)">二审完结</button></div></div></li>
		       	</webres:displaycontroller>
		        <webres:displaycontroller elementId="LOGIC_TRSTART_3WANJIE" description="调拨发起单三审完结">
			       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save4" onclick="submitForm(3)">三审完结</button></div></div></li>
			    </webres:displaycontroller>   
			    <webres:displaycontroller elementId="LOGIC_TRSTART_BOHUI" description="调拨发起单驳回">
			       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save5" onclick="check()">驳回</button></div></div></li>
		       </webres:displaycontroller>  
		       <li><div class="button"><div class="buttonContent"><button type="button" class="print" onclick="CloseDialog()">关闭</button></div></div></li>
				</ul>
			</div>
		</div>
		<script type="text/javascript">
		var ItemStateList = ItemStateData.Rows;
    var column1 = [
                   	{ display: 'id', name: 'id',type: 'string',hide:1},
    				{ display: 'materialsid', name: 'materialsid',hide:1,width:1},
    				{ display: '<font color="gray">编码</font>', name: 'code',width: 120},
    				{ display: '<font color="gray">名称</font>', name: 'name',width: 120},
    				{ display: '<font color="gray">型号</font>', name: 'spec' ,width: 270},
    				{ display: '<font color="gray">基本单位</font>', name: 'junit' ,width: 100},
    				{ display: '<font color="gray">基本单位库存数量</font>', name: 'affquantity',width: 150 , render: function (item)
        				{
	    					if(item.affquantity!=''&&item.affquantity!=null&&item.unitconvert!=null&&item.unitconvert!=''){
	    						addressGrid.updateCell('inquantity', (item.affquantity/item.unitconvert).toFixed(4), item);
	    					}
							if(item.affquantity==null||item.affquantity==""	){
								return "0.0	";
							}else{
								return item.affquantity;
							}
						}
    				},
    				{ display: '<font color="gray">基本单位出库数量</font>', name: 'jquantity',width: 150, render: function (item)
        				{
    						if(item.jquantity==null||item.jquantity==""	){
    							return "0.0	";
    						}else{
    							return item.jquantity;
    						}
   						}
    				},
   					{ display: '<font color="gray">批次</font>', name: 'batch', width: 120},
    				{ display: '状态<font color="red">*</font>', name: 'status', width: 100,editor: { type: 'select', data: ItemStateList, valueColumnName: 'ItemStateID', displayColumnName: 'ItemStateName',onChanged:getkcQuantity}, 
    					render: function (item)
        					{
        						for (var i = 0; i < ItemStateList.length; i++)
        							{
            							if (ItemStateList[i]['ItemStateID'] == item.status){
          	  								return ItemStateList[i]['ItemStateName'];
            							}
        							}
        						return item.status;
    						}
    				},
    				{ display: '单位<font color="red">*</font>', name: 'unit', width: 100,editor : {type:'selecturl',dataItem:'dataItem',path:'${ctx}/yd/basic/measurementUnit/unitlist.do',valueColumnName: 'unitname', displayColumnName: 'unitname'},
    					render: function (item)
        					{
	 		  					var dataitem = $.parseJSON($("#dataItem").val());
	 		  					if(dataitem!=null){
	 			 					for (var i = 0; i < dataitem.length; i++)
              							{
                  							if (dataitem[i]['unitname'] == item.unit&&dataitem[i]['materialscode']==item.code){
                 	 							addressGrid.updateCell('unitconvert', dataitem[i]['unitconvert'], item);
                      							return dataitem[i]['unitname'];
                  							} 
              							}
	 		  					}
            					return item.unit;
        					}
    				},
       				{ display: '<font color="gray">单位换算率</font>', name: 'unitconvert',width:80},
    				{ display: '<font color="gray">库存数量</font>', name: 'inquantity',width: 100,render:function(item){
    					if(item.inquantity==''||item.inquantity==null){
    						return "0.0";
    					}else{
    						return item.inquantity;	
    					}
    				}},
					{ display: '本次出库数量<font color="red">*</font>', name: 'quantity',width: 150,editor : {type :'float'}, render: function (item)
    					{
	   						if(item.quantity!=''&&item.quantity!=null&&item.unitconvert!=null&&item.unitconvert!=''){
	   							addressGrid.updateCell('jquantity', (item.quantity*item.unitconvert).toFixed(4), item);
	   						}
	   						if(item.quantity==''||item.quantity==null){
	    						return "0.0";
	    					}else{
	    						return item.quantity;	
	    					}
    					}
					},
					{ display: '生产/采购日期<font color="red">*</font>', name: 'scrq', width: 120,editor : {type :'scdate'},render: function (item)
						{
							if(item.scrq!=''&&item.scrq!=null){
					 		item.scrq=formatDate(new Date(item.scrq),"yyyy-MM-dd");
							}
					return item.scrq;	
						}},
				{ display: '有效期<font color="red">*</font>', name: 'yxq', width: 120,editor : {type :'scdate'}, render: function (item)
					{
					  if(item.yxq!=''&& item.yxq!=null){
						  item.yxq=formatDate(new Date(item.yxq),"yyyy-MM-dd");
					  }
						if(item.scrq!=''&&item.scrq!=null&&item.yxq!=null&&item.yxq!=''){
							addressGrid.updateCell('bzq', daysBetween(item.scrq,item.yxq), item);
						}
						if(item.yxq==''||item.yxq==null){
						return "";
					}else{
						return item.yxq;	
					}
				}},
    				{ display: '<font color="gray">保质期(天)</font>', name: 'bzq' ,width: 150}
         		];
    var column2 = [
                   { display: 'id', name: 'id',hide:true},
                   { display: 'materialsid', name: 'materialsid',hide:true,width:1},
                   { display: '<font color="gray">编码</font>', name: 'code',width: 120},
                   { display: '<font color="gray">名称</font>', name: 'name',width: 120},
                   { display: '<font color="gray">型号</font>', name: 'spec' ,width: 270},
                   { display: '<font color="gray">基本单位</font>', name: 'junit' ,width: 150},
					{ display: '<font color="gray">基本单位库存数量</font>', name: 'affquantity',width: 150 },
                   { display: '<font color="gray">基本单位出库数量</font>', name: 'jquantity',width: 150},
                   { display: '<font color="gray">批次</font>', name: 'batch', width: 120},
                   { display: '状态<font color="red">*</font>', name: 'status', width: 100, render: function (item){
                       for (var i = 0; i < ItemStateList.length; i++){
                           if (ItemStateList[i]['ItemStateID'] == item.status){
                         	  return ItemStateList[i]['ItemStateName'];
                           }
                       }
                       return item.status;
                   	}
 					},
                    { display: '单位<font color="red">*</font>', name: 'unit' ,width: 150},
       				{ display: '<font color="gray">单位换算率</font>', name: 'unitconvert',width:80},
 					{ display: '<font color="gray">库存数量</font>', name: 'inquantity',width: 100 },
                    { display: '本次出库数量<font color="red">*</font>', name: 'quantity',width: 150},
                    { display: '生产/采购日期<font color="red">*</font>', name: 'scrq' ,width: 150,render: function (item)
    					{
              			if(item.scrq!=''&&item.scrq!=null){
              	 		item.scrq=formatDate(new Date(item.scrq),"yyyy-MM-dd");
              			}
							return item.scrq;	
					}},
		               { display: '有效期至<font color="red">*</font>', name: 'yxq',width: 150, render: function (item)
    					{
	                	  if(item.yxq!=''&& item.yxq!=null){
	                		  item.yxq=formatDate(new Date(item.yxq),"yyyy-MM-dd");
	                	  }
    						return item.yxq;	
					}},
                    { display: '<font color="gray">保质期(天)</font>', name: 'bzq' ,width: 150}
	              ];
    var column3 = null;
	if ('${xx}' == 1){
		column3 = column1;
	}else {
		column3 = column2;
	}
    addressGrid = $("#dataGrid1").ligerGrid({
		columns: column3,
        enabledEdit : true,
        usePager: true,
		width : '99%',
		pageSize:1000,
		pageSizeOptions:[1000],
		rownumbers : false,
		checkbox : true,
		parms:[{ name : 'id' , value : '${oi.id}'}],
        url : basic_Url+"/griditems.do",
        height : '90%',
		toolbar : {
			items : [ {
				text : '新增',
				disable : true,
				click : function() {
					if($("#outwhcode").val()==''){
						$.dialog.alert("请先选择出库仓库");
						return false;
					}else{
						if('${xx}' == 1) {
							getDG().dialog({
								title:'物料选择',
								width : 800,
								height : 400,
								content: 'url:' + sys_context+'/public/windowalert/itemaff.do?code=' + $("#outwhcode").val(),
								lock : true,
								max : true,
								min : true,
								ok: function(){
									var rows = this.content.getSelected();
									if (rows != null) {
										for (var i = 0; i < rows.length;i++){
											var row = rows[i];
											addressGrid.addRow2({
												code : row.code,
	   											name : row.name,
	   											spec : row.spec,
	   											batch : row.batch,
	   											materialsid:row.bmid,
	   											junit : row.unit,
	   											bzq : row.bzq,
	   											scrq : row.scrq,
	   											yxq : row.yxq,
											});
										}
									}
		           					this.content.Close();
						    		return false;
							    },
							    cancelVal: '关闭',
							    cancel: true 
							}).zindex();
						}
					}
				},
				icon: 'add'
				}, 
				{
					line : true
				}, 
				{
					text : '删除',
					click : function() {
						if ('${xx}' == 1){
							addressGrid.deleteSelectedRow();
						}
					},
					img : '${ctx}/js/ligerUI/skins/icons/delete.gif'
				}]
			}});
				
		/* <c:forEach items="${axxJson}" var="row">
		addressGrid.addRow2({
			id : "${row.id}",
	   		materialsid:"${row.materialsid}",
	   		unitconvert : "${row.unitconvert}",
	   		code : "${row.code}",
	   		name : "${row.name}",
	   		spec : "${row.spec}",
	   		junit : "${row.junit}",
	   		unit : "${row.unit}",
	   		status : "${row.status}",
	   		bzq : "${row.bzq}",
	   		scrq : new Date("${row.scrq}").formatdt('yyyy-MM-dd'),
	   		yxq : new Date("${row.yxq}").formatdt('yyyy-MM-dd'),
	   		quantity : "${row.quantity}",
	   		batch:"${row.batch}",
	   		jquantity : "${row.jquantity}",
	   		affquantity : '${row.affquantity}',
	   		inquantity : '${row.inquantity}'
		});
	    </c:forEach> */
	 
	    
	    /*根据物料状态动态获取库存  */
	    function getkcQuantity(e){
	    	var rowData=addressGrid.getRow($(e).parent()[0]);
	    	 $.ajax({
	      		      url: "${ctx}/yd/logic/otherOutwh/getStorageQuaitity.do",
	      		      global: false,
	      		      type: "POST",
	      		      dataType: "json",
	      		      data: ({
	      		    	maCode : rowData.code,
	      				whCode : $("#outwhcode").val(),
	      				hubCode : rowData.hubCode,
	      				status : rowData.status,
	      				batch : rowData.batch
	      		      }),		     
	      		      success: function(msg){
	      		    	rowData.affquantity = msg;
	      			 	rowData.auto = true;
	      			 	addressGrid.updateCell('affquantity',msg,rowData);
	      		      }
	      	   });
	    } 
	    
		/*计算两个日期之间的天数（含当天）*/
		function daysBetween(DateOne,DateTwo)
		{   
		    var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));  
		    var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);  
		    var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));  
		  
		    var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'));  
		    var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1);  
		    var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-'));  
		  
		    var days=((Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear) - Date.parse(OneMonth+'/'+OneDay+'/'+OneYear))/86400000)+1;  //包含当天
		    return days;
		}
    </script>
	</form>
</body>
</html>
